package com.taotao.cart.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import com.taotao.cart.bean.Item;
import com.taotao.cart.mapper.CartMapper;
import com.taotao.cart.pojo.Cart;
@Transactional
@Service
public class CartService {

	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private ItemService itemService;
	
	/**
	 * 用户已登录，添加商品到购物车
	 * 逻辑：判断用户的购物车中是否已经存在该商品，
	 * 如果存在，数量相加，如果不存在，直接新增
	 * @param itemId
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public void addItemToCart(Long itemId,Long userId) throws ClientProtocolException, IOException {
		
		Cart record = new Cart();
		record.setItemId(itemId);
		record.setUserId(userId);
		Cart cart = this.cartMapper.selectOne(record);
		if(cart == null){
			//说明购物车中不存在该商品，直接新增
			record.setCreated(new Date());
			record.setUpdated(record.getCreated());
			record.setNum(1); //TODO 添加的商品数量需要前端页面传递过来
			Item item = this.itemService.queryItemById(itemId);
			record.setItemImage(item.getImages()[0]);//商品主图
			record.setItemPrice(item.getPrice());
			record.setItemTitle(item.getTitle());
			this.cartMapper.insertSelective(record);
		}else{
			//说明购物车中已经存在，数量相加
			cart.setNum(cart.getNum() + 1);//TODO 添加的商品数量需要前端页面传递过来
			this.cartMapper.updateByPrimaryKeySelective(cart);
		}
		
		
	}

	/**
	 * 根据用户id查询购物车列表
	 * @param id
	 * @return
	 */
	public List<Cart> queryCartListByUserId(Long userId) {
		Cart record = new Cart();
		record.setUserId(userId);
		return this.cartMapper.select(record);
	}
	
	/**
	 * 更新购物车商品数量
	 * @param itemId
	 * @param id
	 * @param num
	 */
	public Integer updateCart(Long itemId, Long userId, Integer num) {
		//update tb_cart set num = num where itemId = itemId and userId = userId
		Cart record = new Cart();
		record.setNum(num);
		record.setUpdated(new Date());
		Example example = new Example(Cart.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("itemId", itemId);
		criteria.andEqualTo("userId", userId);
		return this.cartMapper.updateByExampleSelective(record, example);
	}

	/**
	 * 删除单个购物车商品
	 * @param itemId
	 * @param userId
	 */
	public void deleteItemToCart(Long itemId, Long userId) {
		Cart record = new Cart();
		record.setItemId(itemId);
		record.setUserId(userId);
		this.cartMapper.delete(record);
	}
}
